package com.quartz.mq.config;

import com.quartz.mq.business.service.RabbitQuartzService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <h3>partitionjob</h3>
 * <p>RabbitConfig rabbit 配置</p>
 * Spring Boot中消息接受处理完后，若无异常，则由Spring Boot发送消息接受确认。
 * spring.rabbitmq.listener.prefetch控制QoS。
 * @author : hduong
 * @version : 1.0
 * @date : 2019-12-19 18:00
 **/
@Configuration
@EnableRabbit
public class RabbitConfig {
    private final Logger LOGGER = LoggerFactory.getLogger(RabbitConfig.class);

    public static final String ORDER_ROUTING_KEY = "order_key";

    public static final String ORDER_QUEUE = "order_queue";

    public static final String ORDER_EXCHANGE = "order_exchange";

    /**
     * 声明 订单队列
     *
     * @param
     * @return : org.springframework.amqp.core.Queue
     * @date : 2019/12/19 18:03
     * @author : hduong
     */
    @Bean
    public Queue orderQueue() {
        return new Queue(ORDER_QUEUE);
    }

    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(ORDER_EXCHANGE);
    }

    /**
     * 绑定 ：  队列 到 交换机 使用 路由
     *
     * @return
     */
    @Bean
    public Binding bindingExchangeQueue() {
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(ORDER_ROUTING_KEY);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory,
                                         RabbitQuartzService rabbitQuartzService) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        //发送确认的回调方法 配合 rabbitmq.publisher-confirms = true
        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> {
            if (b) {
                LOGGER.info("Send OK!");
            } else {
                LOGGER.error("Send failed!" + s);
            }
        });
        rabbitTemplate.setMessageConverter(messageConverter());

        return rabbitTemplate;
    }

    /**
     * 信息转换器
     *
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

}
